package com.rpc.protocol.http;

import com.rpc.framework.URL;
import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;

/**
 * @Author:cxy
 * @Date:2021/1/22 20:57
 */
public class HttpServer {

    public void start(URL url){
        //启动tomcat,jetty
        Tomcat tomcat = new Tomcat();

        Service service = tomcat.getServer().findService("Tomcat");
        //创建端口连接
        Connector connector = new Connector();
        connector.setPort(url.getPort());

        //创建执行引擎
        Engine engine = new StandardEngine();
        engine.setDefaultHost(url.getHostname());

        Host host = new StandardHost();
        host.setName(url.getHostname());

        //设置上下文和监听器
        String contextPath = "";
        Context context = new StandardContext();
        context.setPath(contextPath);
        context.addLifecycleListener(new Tomcat.FixContextListener());

        host.addChild(context);
        //<执行引擎 :host{context}>
        engine.addChild(host);

        //<服务:<执行引擎 :host{context}>>
        service.setContainer(engine);
        //<服务:连接>
        service.addConnector(connector);
        //dispatcher分发路由
        tomcat.addServlet(contextPath, "dispatcher", new DispatcherServlet());
        context.addServletMappingDecoded("/*", "dispatcher");

        try {
            tomcat.start();
            tomcat.getServer().await();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }

    }
}
